<template>
  <div>
    <div class="vip-member-wrap">
      <div class="vip-content">
        <div class="search-box">
          <div class="input-box">
            <input
              class="input"
              v-model.trim="search"
              type="text"
              @keyup.enter="onSearch"
              placeholder="请输入用户ID/用户手机号码"
            />
            <img
              class="image"
              src="@/assets/images/home/input-clear.png"
              alt=""
              @click="handleClearInput"
              v-if="search"
            />
          </div>
          <el-button
            class="search-btn"
            @click="onSearch"
            :loading="searchLoading"
            :disabled="searchLoading"
          >
            {{ searchLoading ? '查询中...' : '查询' }}
          </el-button>
        </div>
        <div
          class="card-box"
          :style="{
            background: `url(${memberImg})`
          }"
          v-show="isShowNodes"
        >
          <div class="title-box">
            <div class="name-desc-image">
              <img class="image" src="@/assets/images/vipMember/vip-icon.png" alt="" />
              <div class="name-desc">
                <div class="name">{{ memberData.real_name }}</div>
                <div class="desc" v-if="memberData.grade">{{ memberData.grade.name }}</div>
              </div>
            </div>
            <div class="number" v-if="memberData.user_id">
              {{ hiddenPhoneNumber(memberData.user_id) }}
            </div>
          </div>
          <div class="phonenumber" v-if="memberData.mobile">
            联系电话：{{ hiddenPhoneNumber(memberData.mobile) }}
          </div>
          <div class="birthday">生日：{{ memberData.birthday }}</div>
          <div class="money-integral-coupon">
            <div class="item-box">
              <div class="label">余额</div>
              <div class="value">￥{{ memberTotalMoney }}</div>
            </div>
            <div class="item-box">
              <div class="label">积分</div>
              <div class="value">{{ memberData.points }}</div>
            </div>
            <div class="item-box">
              <div class="label">优惠券</div>
              <div class="value">{{ memberData.coupon_num }}</div>
            </div>
            <div class="loss-img-box" v-if="memberData.status == 0">
              <img src="@/assets/images/vipMember/loss.png" alt="" />
            </div>
          </div>
        </div>
        <div class="vip-option-box">
          <div
            class="option-item"
            v-for="(item, index) in vipOptionsList"
            :key="item.name"
            @click="handleAction(index)"
            :class="{
              loading: index === 4 && unhookLoading,
              disabled: index === 4 && unhookLoading
            }"
          >
            <img class="image" :src="item.image" alt="" />
            <div class="desc">
              {{ index === 4 && unhookLoading ? '处理中...' : item.name }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <CardRefundDialog
      v-model:visible="memberDialogData.isShowCardRefundDialog"
      @onConfirm="handleSubmitRefundCard"
      :memberData="memberData"
    />
    <CreateVipDialog
      v-model:visible="memberDialogData.isShowCreateVipDialog"
      @onCancel="handleCreateVipCancel"
      @onSuccess="handleCreateVipSuccess"
    />

    <CheckCouponDialog
      v-model:visible="memberDialogData.isShowCheckCouponDialog"
      :memberId="memberUserId"
    />

    <RechargeBalanceDialog
      v-model:visible="memberDialogData.isShowRechargeBalanceDialog"
      :memberId="memberUserId"
      @onSuccess="refreshMemberInfo"
    />

    <IntegralAdjustmentDialog
      v-model:visible="memberDialogData.isShowIntegralAdjustmentDialog"
      @onConfirm="refreshMemberInfo"
      :memberId="memberUserId"
      :currentPoints="memberData.points"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
//   import { useStore } from 'pinia'
import { ElMessage } from 'element-plus'
import CardRefundDialog from './components/CardRefundDialog.vue'
import CreateVipDialog from './components/CreateVipDialog.vue'
import CheckCouponDialog from './components/CheckCouponDialog.vue'
import RechargeBalanceDialog from './components/RechargeBalanceDialog.vue'
import IntegralAdjustmentDialog from './components/IntegralAdjustmentDialog.vue'

// 引入会员接口api
import * as memberApi from '@/api/member'
import { isEmpty, throttle, hiddenPhoneNumber } from '@/utils/toolsValidate'
import { mathAdd, strNumberToFixed } from '@/utils/mathjsTool'

// 路由和状态管理
const router = useRouter()
//   const store = useStore()

// 响应式数据
const search = ref('')
const memberUserId = ref('')
const memberData = ref({})
const memberTotalMoney = ref(0)
const memberImg = ref(new URL('@/assets/images/vipMember/vip-bgimg.png', import.meta.url).href)
const searchLoading = ref(false)
const unhookLoading = ref(false)

// 会员操作选项列表
const vipOptionsList = ref([
  {
    image: new URL('@/assets/images/vipMember/yuechongzhi-icon.png', import.meta.url).href,
    name: '余额充值'
  },
  {
    image: new URL('@/assets/images/vipMember/jifenshangcheng-icon.png', import.meta.url).href,
    name: '积分商城'
  },
  {
    image: new URL('@/assets/images/vipMember/chakanyouhuiquan-icon.png', import.meta.url).href,
    name: '查看优惠券'
  },
  {
    image: new URL('@/assets/images/vipMember/xinzenghuiyuan-icon.png', import.meta.url).href,
    name: '新增会员'
  },
  {
    image: new URL('@/assets/images/vipMember/guashi-icon.png', import.meta.url).href,
    name: '挂失'
  },
  {
    image: new URL('@/assets/images/vipMember/tuika-icon.png', import.meta.url).href,
    name: '退卡'
  },
  {
    image: new URL('@/assets/images/vipMember/chongzhijilu-icon.png', import.meta.url).href,
    name: '充值记录'
  },
  {
    image: new URL('@/assets/images/vipMember/tuikajilu-icon.png', import.meta.url).href,
    name: '退卡记录'
  }
])

// 弹窗状态管理
const memberDialogData = reactive({
  isShowCardRefundDialog: false,
  isShowCreateVipDialog: false,
  isShowCheckCouponDialog: false,
  isShowRechargeBalanceDialog: false,
  isShowIntegralAdjustmentDialog: false
})

// 计算属性
const isShowNodes = computed(() => !isEmpty(memberData.value))

// 生命周期钩子
onMounted(() => {
  if (router.currentRoute.value.query.phone) {
    search.value = router.currentRoute.value.query.phone
    onSearch()
  }
})

// 搜索提交事件
const onSearch = throttle(() => {
  if (!search.value) return

  searchLoading.value = true
  memberApi
    .searchMemberDetail({ search: search.value })
    .then(res => {
      if (res.status === 200) {
        if (isEmpty(res.data.detail)) {
          ElMessage.error('未查询到会员信息哦')
          return
        }
        memberUserId.value = String(res.data.detail.user_id)
        memberData.value = res.data.detail
        memberTotalMoney.value = strNumberToFixed(
          mathAdd(memberData.value.balance, memberData.value.bonus_balance)
        )
        // 区分显示解挂还是挂失的状态
        memberImg.value =
          memberData.value.status === 1
            ? new URL('@/assets/images/vipMember/vip-bgimg.png', import.meta.url).href
            : new URL('@/assets/images/vipMember/loss-status.png', import.meta.url).href
        vipOptionsList.value[4].name = memberData.value.status === 1 ? '挂失' : '解挂'
      }
    })
    .catch(error => {
      console.error('查询会员信息失败:', error)
      ElMessage.error('查询失败，请重试')
    })
    .finally(() => {
      searchLoading.value = false
    })
}, 300)

// 清空输入框
const handleClearInput = () => {
  search.value = ''
}

// 选中对应的操作选项
const handleAction = index => {
  // 如果挂失/解挂操作正在进行中，直接返回
  if (index === 4 && unhookLoading.value) {
    return
  }

  // 跳转到充值记录页面
  if (index === 6) {
    return router.push({
      name: 'RechargeRecord'
    })
  }
  // 跳转到退卡记录页面
  if (index === 7) {
    return router.push({
      name: 'CardRefundRecord'
    })
  }
  // 如果没有搜索会员提示然后return
  if (!memberUserId.value && index !== 3) {
    ElMessage.warning('请先搜索查询会员信息')
    return
  }

  // 挂失||解挂
  if (index === 4) {
    unhookLoading.value = true
    return memberApi
      .memberUnhook({
        userId: memberUserId.value,
        status: memberData.value.status === 1 ? 0 : 1
      })
      .then(res => {
        if (res.status === 200) {
          ElMessage.success(memberData.value.status === 1 ? '挂失成功' : '解挂成功')
          refreshMemberInfo()
          vipOptionsList.value[4].name = memberData.value.status === 1 ? '挂失' : '解挂'
        }
      })
      .catch(error => {
        console.error('挂失/解挂操作失败:', error)
        ElMessage.error('操作失败，请重试')
      })
      .finally(() => {
        unhookLoading.value = false
      })
  }
  // 打开对应的弹窗组件
  const ACTION_TYPE_MAP = {
    // 打开会员充值的弹窗
    0: 'isShowRechargeBalanceDialog',
    // 打开积分调整弹窗组件
    1: 'isShowIntegralAdjustmentDialog',
    // 显示查看优惠券的弹窗组件
    2: 'isShowCheckCouponDialog',
    // 打开新增会员操作的弹窗组件
    3: 'isShowCreateVipDialog',
    // 显示退卡操作的弹窗组件
    5: 'isShowCardRefundDialog'
  }
  memberDialogData[ACTION_TYPE_MAP[index]] = Boolean(ACTION_TYPE_MAP[index])
}

// 退卡操作
const handleSubmitRefundCard = throttle(val => {
  memberApi.memberDelete({ ...val, userId: memberUserId.value }).then(res => {
    if (res.status === 200) {
      ElMessage.success('退卡成功')
      // 刷新当前会员信息的数据
      memberData.value = {}
    }
  })
}, 300)

// 刷新当前会员信息的数据
const refreshMemberInfo = () => {
  onSearch()
}

// 处理新增会员取消
const handleCreateVipCancel = () => {
  // 可以在这里添加取消后的逻辑
}

// 处理新增会员成功
const handleCreateVipSuccess = () => {
  // 新增会员成功后，可以清空当前搜索的会员信息
  memberData.value = {}
  memberUserId.value = ''
  ElMessage.success('新增会员成功，请重新搜索查看会员信息')
}
</script>
<style lang="scss" scoped>
.vip-member-wrap {
  width: 1600px;
  height: 986px;
  background: #ffffff;
  border-radius: 20px;
  box-shadow: 3px 0px 24px 0px rgba(0, 0, 0, 0.16);
  box-sizing: border-box;
  padding-top: 50px;
  .vip-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: flex-start;
    .search-box {
      display: flex;
      align-items: center;
      .input-box {
        width: 394px;
        height: 48px;
        background: #ffffff;
        border: 1px solid #d2d2d2;
        border-radius: 12px;
        box-sizing: border-box;
        padding: 0 20px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .input {
          width: 350px;
          font-size: 14px;
          font-family:
            PingFang SC,
            PingFang SC-Regular;
          font-weight: 400;
          text-align: left;
          color: #333333;
          outline: none;
          border: none;
        }
        .image {
          flex-shrink: 0;
          width: 24px;
          height: 24px;
          cursor: pointer;
        }
      }
      .search-btn {
        width: 96px;
        height: 48px;
        background: #7c0a03;
        border-radius: 12px;
        font-size: 18px;
        font-family:
          PingFang SC,
          PingFang SC-Regular;
        font-weight: 400;
        color: #ffffff;
        margin-left: 20px;
        border: none;

        &:hover {
          background: #8a0b04;
        }

        &:disabled {
          background: #cccccc;
          cursor: not-allowed;
        }
      }
    }
  }
  .card-box {
    width: 663px;
    height: 398px;
    box-sizing: border-box;
    // background: url('../../assets/images/vipMember/vip-bgimg.png');
    background-size: cover;
    padding: 32px 32px 0 32px;
    margin-top: 60px;
    border-radius: 12px;
    .title-box {
      display: flex;
      align-items: flex-start;
      justify-content: space-between;
      .name-desc-image {
        display: flex;
        align-items: center;
        .image {
          flex-shrink: 0;
          width: 47px;
          height: 48px;
          margin-right: 16px;
        }
        .name-desc {
          .name {
            font-size: 31px;
            font-family:
              PingFang SC,
              PingFang SC-Bold;
            font-weight: 700;
            text-align: left;
            color: #ffe2c2;
          }
          .desc {
            font-size: 15px;
            font-family:
              PingFang SC,
              PingFang SC-Regular;
            font-weight: 400;
            text-align: left;
            color: #efc291;
            margin-top: 10px;
          }
        }
      }
      .number {
        font-size: 19px;
        font-family:
          PingFang SC,
          PingFang SC-Regular;
        font-weight: 400;
        color: #a1a1a1;
      }
    }
    .phonenumber,
    .birthday {
      font-size: 18px;
      font-family:
        PingFang SC,
        PingFang SC-Regular;
      font-weight: 400;
      text-align: left;
      color: #ffe2c2;
    }
    .phonenumber {
      margin-top: 50px;
    }
    .birthday {
      margin-top: 30px;
    }
    .money-integral-coupon {
      display: flex;
      align-items: center;
      // margin-top: 30px;
      height: 220px;
      .item-box {
        font-family:
          PingFang SC,
          PingFang SC-Regular;
        font-weight: 400;
        text-align: left;
        color: #ffe2c2;
        margin-right: 40px;
        .label {
          font-size: 15px;
        }
        .value {
          font-size: 24px;
          margin-top: 10px;
        }
      }
      .loss-img-box {
        width: 46%;
        margin-bottom: 30px;
        display: flex;
        justify-content: flex-end;
        img {
          width: 118px;
          height: 112px;
        }
      }
    }
  }
  .vip-option-box {
    width: 980px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    .option-item {
      width: 200px;
      height: 100px;
      background: #ffffff;
      border: 1px solid #d2d2d2;
      border-radius: 20px;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      padding-left: 16px;
      margin-top: 80px;
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover:not(.disabled) {
        border-color: #7c0a03;
        box-shadow: 0 2px 8px rgba(124, 10, 3, 0.1);
      }

      &.loading {
        background: #f5f5f5;
        border-color: #cccccc;
        cursor: not-allowed;

        .image {
          opacity: 0.6;
        }

        .desc {
          color: #999999;
        }
      }

      &.disabled {
        background: #f5f5f5;
        border-color: #cccccc;
        cursor: not-allowed;

        .image {
          opacity: 0.6;
        }

        .desc {
          color: #999999;
        }
      }

      .image {
        flex-shrink: 0;
        width: 48px;
        height: 48px;
        margin-right: 16px;
        transition: opacity 0.3s ease;
      }

      .desc {
        font-size: 18px;
        font-family:
          PingFang SC,
          PingFang SC-Bold;
        font-weight: 700;
        text-align: left;
        color: #333333;
        transition: color 0.3s ease;
      }
    }
  }
}
</style>
